<template>
  <el-dialog
    :title="dialogType==1?'添加分类':'修改分类'"
    :visible.sync="value"
    width="40%"
    :before-close="()=>{ resetForm('ruleForm') }"
  >
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px">
      <el-form-item label="分类名称" prop="name">
        <el-input v-model="ruleForm.name" />
      </el-form-item>

      <el-form-item label="排序" prop="sort">
        <el-input v-model="ruleForm.sort" type="number" />
        <p class="hint">请输入数字，序号越大排序越靠前</p>
      </el-form-item>

      <el-form-item label="开启状态" prop="status">
        <el-switch v-model="ruleForm.status" :active-value="1" :inactive-value="0" />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="resetForm('ruleForm')">取 消</el-button>
      <el-button type="primary" @click="submitForm('ruleForm')">{{ dialogType==1?'确 定':'保 存' }}</el-button>
    </span>
  </el-dialog>
</template>

<script>

export default {
  props: {
    value: {
      type: Boolean,
      default: false
    },
    dialogType: {
      type: Number,
      default: 1
    },
    editData: {
      type: Object,
      default: () => { return {} }
    }
  },
  data() {
    return {
      editId: '',
      ruleForm: {
        name: '',
        status: 1,
        sort: 1
      },
      rules: {
        name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    editData: {
      handler: function(newVal) {
        if (this.dialogType === 2) {
          const { id, name, status, sort } = newVal
          this.ruleForm.name = name
          this.ruleForm.status = Number(status)
          this.ruleForm.sort = sort
          this.ruleForm.id = id
        } else {
          this.ruleForm = {
            name: '',
            status: 1,
            sort: 1
          }
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$request.post('/admin/goods_category/save', this.ruleForm).then(res => {
            this.$emit('input', false)
            this.$emit('success')
          }).catch()
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].clearValidate()
      this.$emit('input', false)
    }
  }
}
</script>

<style lang="scss" scoped>
    .hint{
        margin: 0;
        padding: 0;
        color: #aaa;
        font-size: 12px;
    }
</style>
